//客户端
var socket = io();



//成功连接
socket.on('connect', () => {
    login();
});


socket.on('reconnect', () => {
    document.getElementById('messages').innerHTML = '';
});



function login() {
    var input = prompt('输入用户名');
    //input = new Date().getTime();
    if (!input || input == '') {
        alert('必须输入用户名');
        login();
        return;
    }
    var obj = {
        type: 'login',
        value: input
    }

    //转string
    var data = JSON.stringify(obj);
    socket.emit('msg', data); //发送登录信息.

}

document.getElementById('send').addEventListener('click', function () {
    var str = document.getElementById('m').value;
    var obj = {
        type: 'answer',
        value: str
    }

    var strText = JSON.stringify(obj);

    socket.emit('msg', strText);
    document.getElementById('m').value = "";
});


//客户端接收到服务器消息
socket.on('msg', data => {
    //appendText('服务器发送:' + data);
    console.log(data);
    var obj = JSON.parse(data);
    action(obj);

});

/**
 * 登录消息接收
 * @param {Object} obj 
 * type
 * success  0 : 成功  1:失败
 * data  
 */
function successLogin(obj) {
    if (obj.success == 0) {
        document.getElementById('name').innerText = '登录成功:' + obj.data;
    } else {
        alert(obj.data);
    }
}

//接收题目
function acceptQuestion(obj) {
    var data = obj.data;
    appendText(JSON.stringify(data));
}

function getAnswer(obj) {
    var data = obj.data;
    alert(data);
}

function rightQuestion(obj) {
    var data = obj.data;
    appendText(JSON.stringify(data));
}

//输出排行榜
function logSort(obj) {
    var data = obj.data;
    for (let i = 0; i < data.length; i++) {
        const user = data[i];
        var str = `名字:${user.name},分数${user.number}`;
        appendText(str);
    }
}


function action(data) {
    switch (data.type) {
        case 'login':
            successLogin(data);
            break;
        case 'sendQuestion':
            acceptQuestion(data);
            break;
        case 'answer':
            getAnswer(data);
            break;
        case 'rightQuestion':
            rightQuestion(data);
            break;
        case 'sort':
            logSort(data);
            break;
        default:
            break;
    }
}


function appendText(str) {
    var li = document.createElement('li');
    li.innerText = str;
    document.getElementById('messages').appendChild(li);
}